/**
 * @param {number[][]} intervals
 * @return {number[][]}
 * 输入：intervals = [[1,3],[2,6],[8,10],[15,18]]
输出：[[1,6],[8,10],[15,18]]
解释：区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
 */
var merge = function (intervals) {
  const res = []
  const mergeTem = arr => {
    let temarr = []
    let indexArr = []
    for (let i = arr[0]; i <= arr[arr.length - 1]; i++) {
      temarr.push(i)
    }
    if (res.length === 0) {
      res.push(temarr)
    } else {
      res.forEach((item, index) => {
        let mergeArr = [...item, ...temarr]
        const setArr = [...new Set(mergeArr)]
        if (setArr.length !== mergeArr.length) {
          indexArr.push(index)
        }
      })
      if (indexArr.length > 0) {
        const sortArr = []
        while (indexArr.length) {
          let index = indexArr.pop()
          let delArr = res.splice(index, 1)
          sortArr.push(...delArr[0], ...temarr)
        }
        res.push([...new Set(sortArr.sort((a, b) => a - b))])
      } else {
        res.push(temarr)
      }
    }
  }
  intervals.forEach(item => mergeTem(item))
  return res.map(item => [item[0], item[item.length - 1]])
}
